﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Security;

namespace RestaurantManagerWebApp.Pages.UserManagement
{
    public partial class UserLogin : System.Web.UI.Page
    {
        string connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void ValidateUser(object sender, AuthenticateEventArgs e)
        {
            // Initialize FormsAuthentication, for what it's worth
            FormsAuthentication.Initialize();

            // Create our connection and command objects
            SqlConnection conn = new SqlConnection(connection);
            string query = "Select role from Users where u_id=@username AND password=@password";
            SqlCommand cmd = new SqlCommand(query, conn);

            // Fill our parameters
            cmd.Parameters.AddWithValue("@username", Login1.UserName);
            cmd.Parameters.AddWithValue("@password", Login1.Password);


            // Execute the command
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                this.Session["Username"] = Login1.UserName;
                if (dr["role"].ToString() == "Admin")
                {
                    Response.Redirect("~/Pages/AdminMain.aspx");
                }
                else
                {
                    Response.Redirect("~/Pages/Main.aspx");
                }
                
                
            }
            else
            {
                // Never tell the user if just the username is password is incorrect.
                // That just gives them a place to start, once they've found one or
                // the other is correct!
                Login1.FailureText = "Username / password incorrect. Please try again.";
            }

            dr.Close();
            conn.Close();
        }
    }

}